﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;
using System.Text;

public partial class Controls_Activity_UserSelect : BaseUserControl
{
    public UserSelectEventHandler OnUserSelectOk;

    public EventHandler OnSelect;

    private OrgTreeAccess orgTreeAccess;

    private SqlCodeConfig codeConfig;

    public string m_Table = "PMS_User"; 

    string sql = @"select a.*,
                        (select top 1 OrgID from T_OrgUser where UserID=a.UserID) OrgID, 
                        (select top 1 Subject from T_OrgTree where OrgID=(select OrgID from T_OrgUser where UserID=a.UserID)) OrgName,
						(select CodeName from T_CodeConfig where CodeValue=a.GroupCode  And Category = '" + PMSCodeCategory.PMS_BMZB + @"') GroupName
                        from PMS_User a ";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            orgTreeAccess = new OrgTreeAccess(base.Connection);
            //DataSet ds = orgTreeAccess.LoadTreeData(true, false, OrgTreeAccess.TREE_XINGZHENG);
            DataSet ds = PMSAccess.GetDataSet(this.Connection, "select CodeValue as NodeId,CodeName as Subject,CodeName as Alias,'0' as ParentId from T_CodeConfig where 1=1 and Category = '" + PMSCodeCategory.PMS_BMZB + "' order by CodeValue");
            treeView.Nodes.Clear();
            DataToTree(ds, treeView, null);
            InitData();
        }
        OnSelect += new EventHandler(btnSelect_Click); 
    }
    public void SetTBGroupReadOnly(string groupcode)
    {
        if (string.IsNullOrEmpty(groupcode))
        {
            //this.tbGroup.Enabled = true;
        }
        else
        {
            //this.tbGroup.SelectByValue = groupcode;
            //this.tbGroup.Enabled = false;
        }
    }
    private void InitData()
    { 
        //codeConfig = new SqlCodeConfig(this.Connection);
        //DataSet ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_BMZB);
        
        //if (ds != null && ds.Tables.Count > 0)
        //{
        //    tbGroup.DataSource = ds.Tables[0];
        //    tbGroup.DataTextField = "CodeName";
        //    tbGroup.DataValueField = "CodeValue";
        //    tbGroup.DataBind();
        //}
    }
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        hfModalPopup.Value = "SelectItem";
        literalModalPopup.Text = "请选择人员";
        gridViewSelect.Visible = true;
        string strsql = sql + " where 1=1 ";
        if (treeView.SelectedNode!=null)
            strsql += " and a.GroupCode='" + treeView.SelectedNode.Value + "'";
        FillSelectGirdView(0, strsql);
        modalPopup.Show();
    }
    protected void gridViewSelect_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
        }
    }

    protected void gridViewSelect_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillSelectGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string cmdText = sql + " where 1=1 ";

        if (treeView.SelectedNode != null)
            cmdText += " and a.GroupCode='" + treeView.SelectedNode.Value + "'";
        if (!string.IsNullOrEmpty(tbUsername.Text.Trim()))
        {
            cmdText += " and a.UserName like '%{0}%' and ";
            cmdText = string.Format(cmdText, tbUsername.Text.Trim().Replace("'", ""));
        } 
        if (!string.IsNullOrEmpty(tbBarcode.Text.Trim()))
        {
            cmdText += " and a.Barcode = '{0}' ";
            cmdText = string.Format(cmdText, tbBarcode.Text.Trim().Replace("'", ""));
        }
        if (cmdText.EndsWith("and "))
        {
            cmdText = cmdText.TrimEnd(new char[] { 'a', 'n', 'd', ' ' });
        } 

        FillSelectGirdView(0, cmdText);
    }
    protected void FillSelectGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        ViewState[this.ClientID + "cmdText"] = cmdText;
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        gridViewSelect.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        gridViewSelect.ShowFooter = true;
        gridViewSelect.NavigationData = splitPage.GetNavigationData(currentPage);
        gridViewSelect.DataSource = ds.Tables[0];
        gridViewSelect.DataBind();
    }
    protected void treeView_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (treeView.SelectedNode != null)
        { 
            string cmdText = sql + @"  where 1=1 and  a.GroupCode='" + treeView.SelectedNode.Value + "' order by a.CreateTime desc";
            //cmdText = string.Format(cmdText, treeView.SelectedNode.Value);
            FillSelectGirdView(0, cmdText);
        }
    }
    protected void btnModalPopupOK_Click(object sender, EventArgs e)
    {
        StringBuilder str = new StringBuilder();

        for (int i = 0; i < gridViewSelect.Rows.Count; i++)
        {
            HtmlInputCheckBox ck = ((HtmlInputCheckBox)gridViewSelect.Rows[i].Cells[0].FindControl("UserID"));
            if (ck.Checked)
            {
                str.Append("'").Append(ck.Value).Append("',");
            }
        }
        if (str.Length == 0)
        {
            base.Alert("请选择人员,否则点击取消");
            modalPopup.Show();
            return;
        }
        else
        {

            string cmdText = sql + "where a.UserID in({0})";
            str = str.Remove(str.Length - 1, 1);
            cmdText = string.Format(cmdText, str);
            PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, cmdText, m_Table);
            //DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
            //foreach (DataRow dr in ds.Tables[0].Rows)
            //{
            //    if (SessionManager.DataSet.Tables[m_SubTable].Select("UserID='" + dr["UserID"].ToString() + "'").Length > 0) continue;
            //    DataRow _dr = SessionManager.DataSet.Tables[0].NewRow();
            //    _dr["UserID"] = dr["UserID"];
            //    _dr["UserName"] = dr["UserName"];
            //    _dr["OrgID"] = dr["OrgID"];
            //    _dr["OrgName"] = dr["OrgName"];
            //    _dr["GroupCode"] = dr["GroupCode"];
            //    _dr["GroupName"] = dr["GroupName"];
            //    SessionManager.DataSet.Tables[m_SubTable].Rows.Add(_dr);
            //}            
            //触发事件
            if (OnUserSelectOk != null)
            {
                UserSelectEventArgs ev = new UserSelectEventArgs();
                ev.SelectDataSet = SessionManager.DataSet;
                OnUserSelectOk(this.ID, ev);
            } 
        }
    }
    /// <summary>
    /// 数据集转换到节点
    /// </summary>
    /// <param name="dataSet"></param>
    /// <param name="treeView"></param>
    /// <param name="node"></param>
    private void DataToTree(DataSet dataSet, TreeView treeView, TreeNode node)
    {
        String filter;
        if (node != null)
            filter = "ParentID = '" + node.Value + "'";
        else
            filter = "ParentID = '0'";

        foreach(DataRow row in dataSet.Tables[0].Rows)
        { 
            TreeNode child = new TreeNode();
            child.Value = row["NODEID"].ToString();
            child.Text = row["SUBJECT"].ToString();
            child.ToolTip = row["Alias"].ToString();
            //child.NavigateUrl = "#";

            if (node != null)
            {
                node.ChildNodes.Add(child);
                if (node.Depth < 1)
                {
                    node.Expand();
                }
                else
                {
                    node.Collapse();
                }
            }
            else
                treeView.Nodes.Add(child);
        }
    }


    /// <summary>
    /// 返回当前节点的上一个节点
    /// </summary>
    public TreeNode FirstNode(TreeNode node)
    {
        if (node.ChildNodes.Count > 0)
        {
            return node.ChildNodes[0];
        }
        else
        {
            return null;
        }
    }


    /// <summary>
    /// 返回当前节点的下一个节点
    /// </summary>
    public TreeNode NextNode(TreeNode node)
    {
        if (node.Parent != null)
        {
            for (int i = 0; i < node.Parent.ChildNodes.Count; i++)
            {
                if (node.Parent.ChildNodes[i] == node)
                {
                    if (i < node.Parent.ChildNodes.Count - 1)
                    {
                        return node.Parent.ChildNodes[i + 1];
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            //永远执行不到
            return null;
        }
        else
        {
            return null;
        }
    }


    /// <summary>
    /// 在树中查找节点
    /// </summary>
    protected TreeNode DepthFirstSearch(TreeNode node, string nodeID)
    {
        //do something
        TreeNode result = null;
        if (node.Value == nodeID)
        {
            return node;
        }

        //TreeNode child = child.FirstNode;
        TreeNode child = FirstNode(node);
        while (child != null)
        {
            result = DepthFirstSearch(child, nodeID);
            if (result != null && result.Value == nodeID)
            {
                result.Selected = true;
                return result;
            }
            //child = child.NextNode;
            child = NextNode(child);
        }
        return result;
    }
 
}
